package com.mjp.learn.multi.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 重入锁tryLock方法,可以设置等待时间长度,传入参数等待时间,如果不加参数就不等待
 * 结束后需要释放锁
 */
public class Demo02 implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();

    public void run() {
        try {
            if (lock.tryLock(5, TimeUnit.SECONDS)){
                Thread.sleep(TimeUnit.SECONDS.toMillis(6));
            } else {
                System.out.println("get lock failed");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(lock.isHeldByCurrentThread()) lock.unlock();
        }
    }

    public static void main(String[] args) {
        Demo02 demo = new Demo02();
        Thread t1 = new Thread(demo);
        Thread t2 = new Thread(demo);
        t1.start();
        t2.start();
    }
}
